<?php
	require("wwdb.php");
	$retVal = "";
	wwdb();
	$results = mysql_query("SELECT * FROM players WHERE playerName='" . cleanparam("memberName") . "'");
	if ($row = mysql_fetch_assoc($results)) {
		$m = $row["memberID"];
		$s = $row["sesskey"];
		$results = mysql_query("SELECT gameStatus.gameID, playerCount FROM gameStatus INNER JOIN scores ON (gameStatus.gameID=scores.gameID) WHERE scores.memberID=$m AND gameStatus.status=2");
		while ($row = mysql_fetch_assoc($results)) {
			$g = $row["gameID"];
			$p = $row["playerCount"];
			//my last played turn
			$wResults = mysql_query("SELECT MAX(turnNumber) AS t FROM waffle WHERE gameID=$g AND memberID=$m");
			if ($wResults != NULL) {
				$maxW = mysql_fetch_assoc($wResults);
				$myLastPlayed = $maxW["t"] != NULL ? $maxW["t"] : 0;
				$pResults = mysql_query("SELECT * FROM waffle WHERE gameID=$g AND turnNumber=$myLastPlayed");
				$pCount = mysql_num_rows($pResults);
				//next guesser
				$lResults = mysql_query("SELECT MIN(turnNumber) AS t, memberID FROM lettersGuessed WHERE gameID=$g AND letter IS NULL");
				$minL = mysql_fetch_assoc($lResults);
				$nextGuesser = $minL["t"] != NULL ? $minL["t"] : 0;
				$u = "wordWaffle.php?gameID=$g&sesskey=$s";
				$retVal .= "<button class='existingGame' onclick=\"window.location='$u'\">";
				//have I played the most recent letter?
				if ($nextGuesser - 1 > $myLastPlayed && $nextGuesser > 1)
					$retVal .= "Game $g ($myLastPlayed/25)<span class='yourTurn'>[your turn!]</span>";
				//If so, am I the next guesser?
				elseif ($minL["memberID"] == $m && $pCount == $p)
					$retVal .= "Game $g ($nextGuesser/25)<span class='yourTurn'>[your turn!]</span>";
				//otherwise, we're still waiting on someone else
				else
					$retVal .= "Game $g ($nextGuesser/25)";
				$retVal .= "</button>";
			}
		}
	}
	echo $retVal;
?>